import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jss_flutter/module/home/view.dart';
import 'package:jss_flutter/module/my/view.dart';
import 'package:jss_flutter/module/promotions/view.dart';
import 'package:jss_flutter/utils/toast_utils.dart';

import 'logic.dart';

///主页面
class MainPage extends GetView<MainLogic> {
  MainPage({Key? key}) : super(key: key);

  DateTime? _lastPressedAt;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      bottomNavigationBar: _buildBottomNavigationBar(),
      body: WillPopScope(
        onWillPop: () async {
          if (_lastPressedAt == null ||
              DateTime.now().difference(_lastPressedAt!) > const Duration(seconds: 1)) {
            //两次点击间隔超过1秒则重新计时
            _lastPressedAt = DateTime.now();
            toast("再按一次返回退出APP");
            return false;
          } else {
            _lastPressedAt = DateTime.now();
            // 退出app
            Get.back();
          }
          return true;
        },
        child: _buildPageView(),
      ),
    );
  }

  Widget _buildPageView() {
    return PageView(
      physics: const NeverScrollableScrollPhysics(),
      controller: controller.pageController,
      onPageChanged: controller.handlePageChanged,
      children: const <Widget>[
        HomePage(),
        PromotionsPage(),
        MyPage(),
      ],
    );
  }

  Widget _buildBottomNavigationBar() {
    return Obx(
      () => BottomNavigationBar(
        items: controller.bottomTabs,
        currentIndex: controller.state.page,
        type: BottomNavigationBarType.fixed,
        onTap: controller.handleNavBarTap,
        showSelectedLabels: false,
        showUnselectedLabels: false,
      ),
    );
  }
}
